package com.xz.diagnosis.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.diagnosis.domain.DiagnosisPackage;
import com.xz.diagnosis.dto.DiagnosisPackageItemDto;
import com.xz.diagnosis.vo.DiagnosisPackageItemVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xz.diagnosis.mapper.DiagnosisPackageItemMapper;
import com.xz.diagnosis.domain.DiagnosisPackageItem;
import com.xz.diagnosis.service.IDiagnosisPackageItemService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 诊疗套餐项目Service业务层处理
 *
 * @author xz
 * @date 2024-03-14
 */
@Service
public class DiagnosisPackageItemServiceImpl extends ServiceImpl<DiagnosisPackageItemMapper, DiagnosisPackageItem> implements IDiagnosisPackageItemService {
  @Autowired
  private DiagnosisPackageItemMapper diagnosisPackageItemMapper;


  /**
   * 根据套餐ID查询项目列表
   * @param packageId
   * @return
   */
  @Override
  public List<DiagnosisPackageItemVo> selectByPackageId(Long packageId) {
    return diagnosisPackageItemMapper.selectByPackageId(packageId);
  }

  /**
   * 新增诊疗套餐项目
   * @param packageEntity
   * @param dtos
   * @param isUpdate
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void insertForPackage(DiagnosisPackage packageEntity, List<DiagnosisPackageItemDto> dtos, boolean isUpdate) {
    // 如果是更新时调用，那么要删除旧数据添加新的。
    if(isUpdate){
      LambdaQueryWrapper<DiagnosisPackageItem> wrapper = Wrappers.lambdaQuery(DiagnosisPackageItem.class);
      wrapper.eq(DiagnosisPackageItem::getPackageId, packageEntity.getId());
      diagnosisPackageItemMapper.delete(wrapper);
    }
    // 添加新数据
    if(!CollectionUtils.isEmpty(dtos)){
      dtos.forEach(dto ->{
        DiagnosisPackageItem entity = new DiagnosisPackageItem();
        BeanUtils.copyProperties(dto,entity);
        entity.setPackageId(packageEntity.getId());
        entity.setCreateBy(packageEntity.getCreateBy());
        entity.setCreateTime(packageEntity.getUpdateTime());
        entity.setTenantId(packageEntity.getTenantId());
        entity.setDeptId(packageEntity.getDeptId());
        diagnosisPackageItemMapper.insertDiagnosisPackageItem(entity);
      });
    }

  }

  /**
   * 根据套餐ID查询项目列表
   *
   * @param ids 需要删除的诊疗套餐主键
   * @return 结果
   */
  @Override
  public int deleteByPackageIds(Long[] ids) {
    return diagnosisPackageItemMapper.deleteByPackageIds(ids);
  }
}
